//
//  Tools.m
//  Phono
//
//  Created by Fee on 2025/7/4.
//

#import "Tools.h"
#import <CommonCrypto/CommonCryptor.h>

#import <UIKit/UIKit.h>

@implementation Tools

+ (NSString *)bundleId {
    return [[NSBundle mainBundle] bundleIdentifier];
}

+ (BOOL)isEmptyUUID:(NSString *)uuid {
    return [uuid hasPrefix:@"00000000-"] || [Tools isEmpty:uuid];
}

/// 设备id
+ (NSString *)deviceId {
    NSString *deviceId = @"";
    return deviceId;
}

/// 国家代码
+ (NSString *)countryCode {
    NSString *countryCode = [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
    NSLog(@"Country Code: %@", countryCode); // 例如: "US" 或 "CN"}
    return countryCode;
}

/// App版本号
+ (NSString *)appVersion { return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; }

/// appName
+ (NSString *)appName { return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]; }

/// window
+ (UIWindow *)window {
    UIApplication *app = [UIApplication sharedApplication];
    // 遍历所有活跃的 scene
    for (UIWindowScene *scene in app.connectedScenes) {
        if (scene.activationState == UISceneActivationStateForegroundActive) {
            // 获取该 scene 的 keyWindow
            for (UIWindow *window in scene.windows) {
                if (window.isKeyWindow) {
                    return window;
                }
            }
            // 如果没有 keyWindow，返回第一个 window
            if (scene.windows.count > 0) {
                return scene.windows.firstObject;
            }
        }
    }
    
    // 如果没有找到活跃的 scene，尝试获取第一个 scene 的 window
    UIWindowScene *firstScene = (UIWindowScene *)app.connectedScenes.anyObject;
    if (firstScene && firstScene.windows.count > 0) {
        return firstScene.windows.firstObject;
    }
    
    if ([app.delegate respondsToSelector:@selector(window)] && app.delegate.window) return app.delegate.window;
    
    return nil;
}

/// aes 加密
+ (NSString *)encryptAES:(NSString *)content key:(NSString *)key iv:(NSString *)iv {
    // 检查参数有效性
    if (!content || !key || !iv) {
        return nil;
    }
    
    NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
    NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
    
    // 检查密钥和IV长度
    if (keyData.length != kCCKeySizeAES128 && keyData.length != kCCKeySizeAES192 && keyData.length != kCCKeySizeAES256) {
        NSLog(@"密钥长度不正确，应为16、24或32字节");
        return nil;
    }
    
    if (ivData.length != kCCBlockSizeAES128) {
        NSLog(@"IV长度不正确，应为16字节");
        return nil;
    }
    
    // 设置加密参数
    size_t bufferSize = contentData.length + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES,
                                          kCCOptionPKCS7Padding,
                                          keyData.bytes,
                                          keyData.length,
                                          ivData.bytes,
                                          contentData.bytes,
                                          contentData.length,
                                          buffer,
                                          bufferSize,
                                          &numBytesEncrypted);
    
    if (cryptStatus == kCCSuccess) {
        NSData *encryptedData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
        // 返回Base64编码的加密结果
        return [encryptedData base64EncodedStringWithOptions:0];
    }
    
    free(buffer);
    return nil;
}

/// aes 解密
+ (NSString *)decryptAES:(NSString *)base64EncodedString key:(NSString *)key iv:(NSString *)iv {
    // 检查参数有效性
    if (!base64EncodedString || !key || !iv) {
        return nil;
    }
    
    NSData *encryptedData = [[NSData alloc] initWithBase64EncodedString:base64EncodedString options:0];
    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
    NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
    
    // 检查密钥和IV长度
    if (keyData.length != kCCKeySizeAES128 && keyData.length != kCCKeySizeAES192 && keyData.length != kCCKeySizeAES256) {
        NSLog(@"密钥长度不正确，应为16、24或32字节");
        return nil;
    }
    
    if (ivData.length != kCCBlockSizeAES128) {
        NSLog(@"IV长度不正确，应为16字节");
        return nil;
    }
    
    // 设置解密参数
    size_t bufferSize = encryptedData.length + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES,
                                          kCCOptionPKCS7Padding,
                                          keyData.bytes,
                                          keyData.length,
                                          ivData.bytes,
                                          encryptedData.bytes,
                                          encryptedData.length,
                                          buffer,
                                          bufferSize,
                                          &numBytesDecrypted);
    
    if (cryptStatus == kCCSuccess) {
        NSData *decryptedData = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
        return [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
    }
    
    free(buffer);
    return nil;
}

/// 判断一个对象是否是为空
+ (BOOL)isEmpty:(id)obj {
    return obj == nil || [obj isEqual:[NSNull null]]
    || ([obj respondsToSelector:@selector(length)]
        && [obj length] == 0)
    || ([obj respondsToSelector:@selector(count)]
        && [obj count] == 0);
}

/// 字典转字符串
+ (NSString *)dictToString:(NSDictionary *)dict {
    NSError *error;
    // 将 NSDictionary 转换为 JSON 数据
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted | NSJSONWritingWithoutEscapingSlashes error:&error];
    return data ? [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] : @"";
}

/// 字符串转json
+ (id)stringToJson:(NSString *)jsonString {
    if ([self isEmpty:jsonString]) {
        NSLog(@"JSON 字符串为空");
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
    if (error) {
        NSLog(@"JSON 解析错误: %@", error.localizedDescription);
        return nil;
    }
    return jsonObject;
}

/// 随机从数组获取一个对象
+ (id)randomObjectFromArray:(NSArray *)array {
    if ([self isEmpty:array]) return nil;
    return array[arc4random_uniform((uint32_t)array.count)];
}

/// URLEncode
+ (NSString *)urlEncode:(NSString *)url {
    NSCharacterSet *allowedCharacters = [NSCharacterSet characterSetWithCharactersInString:@"!*'();:@&=+$,/?%#[]"].invertedSet;
    NSString *encodedString = [url stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
    NSLog(@"tools-> urlEncode: %@", encodedString);
    return encodedString;
}

@end

